﻿$(function () {
    loadMenu();
    ko.applyBindings(vm, $('#_industry')[0]);
    ko.applyBindings(vm, $('#_country')[0]);
    ko.applyBindings(vm, $('#mnrole')[0]);
    ko.applyBindings(vm, $('#mnaccount')[0]);
    
    $('#IndustryModal').on('hide.bs.modal', function () {
        $(this).find('#IMName').val('');
        $(this).find('#IMDescription').val('');
    });

    $('#FunctionModal').on('hide.bs.modal', function () {
        $(this).find('#FMName').val('');
        $(this).find('#FMDescription').val('');
    });

});

vm.enableDetails = function (item, event) {
    $(event.target).tooltip();
}


vm.Industry = ko.observableArray();
vm.Function = ko.observableArray();

vm.SelectedIndustry = ko.observable();
vm.SelectedFunction = ko.observable();

vm.IndustryName = ko.observable();
vm.Description = ko.observable();

vm.getChild = function (item) {
    setActive('mainItem', item.Name());
    vm.SelectedIndustry = item;
    vm.IndustryName(item.Name());
    vm.Function([]);
    vm.SelectedFunction = null;
    var qrSubitem = new breeze.EntityQuery().from("Industries").where("ParentId", "==", item.UniqueId());
    manager.executeQuery(qrSubitem).then(function (data) {
        data.results.forEach(function (item) {
            vm.Function.push(item);
        });
        $('#subItem').hide();
        $('#itemDescription').hide();
        $('#subItem').fadeIn('slow');
    }).fail(function (e) {
        alert(e);
    });

}
vm.getDescription = function (item) {
    setActive('subItem', item.Name());
    $('#itemDescription').hide();
    $('#itemDescription').fadeIn('slow');
    vm.SelectedFunction = item;
    vm.Description(item.Description());
}
vm.Save = function (item) {
    vm.SelectedFunction.Description(vm.Description());
    saveSingleEntity(vm.SelectedFunction, null);
}
vm.delInd = function (data) {
    if (confirm("Are you sure to delete " + vm.SelectedIndustry.Name() + " ?")) {
        var delarr = Array();
        vm.SelectedIndustry.entityAspect.setDeleted();
        for (var i = 0; i < vm.Function().length; i++) {
            vm.Function()[i].entityAspect.setDeleted();
            delarr.push(vm.Function()[i]);
        }
        delarr.push(vm.SelectedIndustry);
        saveSingleEntity(null, delarr);
        vm.Industry.remove(function (item) { return item.UniqueId() == vm.SelectedIndustry.UniqueId() })
        vm.Function.removeAll();
        vm.Description('');
        $('#subItem').hide();
        $('#itemDescription').hide();
    }
}
vm.delFunc = function (data) {
    if (confirm("Are you sure to delete" + vm.SelectedFunction.Name() + " ?")) {
        vm.SelectedFunction.entityAspect.setDeleted();
        vm.Function.remove(function (item) { return item.UniqueId() == vm.SelectedFunction.UniqueId() })
        saveSingleEntity(vm.SelectedFunction, null);
        vm.Description('');
        $('#itemDescription').hide();
    }
}

var query = new breeze.EntityQuery().from("Industries").where("ParentId", "==", null);
manager.executeQuery(query).then(function (data) {
    data.results.forEach(function (item) {
        vm.Industry.push(item);
    })
    ;
}).fail(function (e) {
    alert(e);
});

function addParent() {
    var newIndustry = manager.createEntity('Industry', { Name: $('#IMName').val(), Description: $('#IMDescription').val() });
    vm.Industry.push(newIndustry);
    saveSingleEntity(newIndustry, null);
    $('#IndustryModal').modal('hide');
}
function addChild() {
    var newFunction = manager.createEntity('Industry', { Name: $('#FMName').val(), Description: $('#FMDescription').val(), Parent: vm.SelectedIndustry });
    //vm.SelectedIndustry.Children.push(newFunction);
    vm.Function.push(newFunction);
    saveSingleEntity(newFunction, null);
    $('#FunctionModal').modal('hide');
}

function setActive(id, name) {
    $('#'+ id + '> div > a').each(function (index, data) {
        if ($.trim(data.text) == $.trim(name)) {
            if (!$(data).hasClass('active')) $(data).addClass('active');            
        } else {
            $(data).removeClass('active');
        }
    });
}

//***************************************
//* The code below is used for Location *
//***************************************

vm.Country = ko.observableArray();
vm.SelectedCountry = ko.observable('');
vm.SelectedProvince = ko.observable('');
vm.SelectedCity = ko.observable('');

var query = new breeze.EntityQuery().from("Locations").where("ParentId", "==", null);
manager.executeQuery(query).then(function (data) {
    data.results.forEach(function (item) {
        vm.Country.push(item);
    });
}).fail(function (e) {
    alert(e);
});

vm.getProvince = function (data) {
    setActive('_country', data.Name());
    vm.SelectedCountry = data;

    ko.cleanNode($('#_provine')[0]);
    ko.applyBindings(data, $('#_provine')[0]);
    $('#_provine').hide();
    $('#_city').hide();
    $('#_provine').fadeIn('slow');

}
vm.getCity = function (data) {
    setActive('_provine', data.Name());
    vm.SelectedProvince = data;
    vm.SelectedCity = '';
    ko.cleanNode($('#_city')[0]);
    ko.applyBindings(data, $('#_city')[0]);
    $('#_city').hide();
    $('#_city').fadeIn('slow');
}
vm.cityselect = function (data) {
    setActive('_city', data.Name());
    vm.SelectedCity = data;
}

vm.addCountry = function () {
    var countryname = prompt("Please enter country name", "Country Name");
    if (countryname == null || $.trim(countryname).length == 0) return;
    
    var match = ko.utils.arrayFirst(vm.Country(), function (country) {
        return country.Name() === countryname;
    });
    if (match == null) {
        var newCountry = manager.createEntity('Location', { Name: countryname});
        vm.Country.push(newCountry);
        saveSingleEntity(newCountry);
    } else {
        alert(countryname + " is existed! Please try with another name");
    } 
}
vm.addProvince = function () {
    var provincename = prompt("Please enter province name", "Province Name");
    if (provincename == null || $.trim(provincename).length == 0) return;

    var match = ko.utils.arrayFirst(vm.SelectedCountry.Children(), function (province) {
        return province.Name() === provincename;
    });
    if (match == null) {
        var newProvince = manager.createEntity('Location', { Name: provincename, Level: 2, Parent: vm.SelectedCountry });
        vm.SelectedCountry.Children().push(newProvince);
        saveSingleEntity(newProvince);
    } else {
        alert(provincename + " is existed! Please try with another name");
    }
}
vm.addCity = function () {
    var citycename = prompt("Please enter city name", "City Name");
    if (citycename == null || $.trim(citycename).length == 0) return;

    var match = ko.utils.arrayFirst(vm.SelectedProvince.Children(), function (city) {
        return city.Name() === citycename;
    });
    if (match == null) {
        var newCity = manager.createEntity('Location', { Name: citycename, Level: 3, Parent: vm.SelectedProvince });
        vm.SelectedProvince.Children().push(newCity);
        saveSingleEntity(newCity);
    } else {
        alert(citycename + " is existed! Please try with another name");
    }
}
vm.delCountry = function () {
    if (vm.SelectedCountry != "") {
        var entityToDeletelvl2 = Array();
        var entityToDeletelvl3 = Array();

        while (vm.SelectedCountry.Children().length > 0) {
            var Children = vm.SelectedCountry.Children()[0];
            entityToDeletelvl2.push(Children);
            while (Children.Children().length > 0) {
                entityToDeletelvl3.push(Children.Children()[0]);
                Children.Children()[0].entityAspect.setDeleted();
            }
            Children.entityAspect.setDeleted();
        }

        vm.Country.remove(vm.SelectedCountry);
        vm.SelectedCountry.entityAspect.setDeleted();
        
        queuingSave(entityToDeletelvl3, entityToDeletelvl2, [vm.SelectedCountry]);
        
        $('#_city').hide();
        $('#_provine').hide();
    } else {
        alert("Select a country first");
    }

}
vm.delProvince = function () {
    if (vm.SelectedProvince != "") {
        if (vm.SelectedProvince.Children().length == 0) {
            vm.SelectedProvince.entityAspect.setDeleted();
            saveSingleEntity(vm.SelectedProvince, null);
            return;
        }
        var entityToDelete = Array();        
        while (vm.SelectedProvince.Children().length > 0) {           
            entityToDelete.push(vm.SelectedProvince.Children()[0]);
            vm.SelectedProvince.Children()[0].entityAspect.setDeleted();
        }

        var index = vm.Country.indexOf(vm.SelectedCountry);
        vm.Country()[index].Children.remove(vm.SelectedProvince);

        queuingSave(entityToDelete, [vm.SelectedProvince], null);

        $('#_city').hide();
    } else {
        alert("Select a province first");
    }
}
vm.delCity = function () {
    if (vm.SelectedCity != "") {
        vm.SelectedCity.entityAspect.setDeleted();
        saveSingleEntity(vm.SelectedCity);
    } else {
        alert("Select a city first");
    }
}

//***************************************
//* The code below is used for Roles *
//***************************************

vm.Roles = ko.observableArray();
vm.Menus = ko.observableArray();
vm.selectdRole = ko.observable('');

var qrRole = new breeze.EntityQuery().from("Roles");
manager.executeQuery(qrRole).then(function (data) {
    data.results.forEach(function (item) {
        vm.Roles.push(item);
    });
}).fail(function (e) {
    alert(e);
});

var qrMenu = new breeze.EntityQuery().from("Menus");
manager.executeQuery(qrMenu).then(function (data) {
    data.results.forEach(function (item) {
        vm.Menus.push(item);
    });
}).fail(function (e) {
    alert(e);
});

vm.addRole = function () {
    var name = prompt("Role name", '');
    if($.trim(name).length > 0){
        var newRole = manager.createEntity('Role', {Name: name});
        saveSingleEntity(newRole,null);
        vm.Roles.push(newRole);
    } else {
        alert('Invalid name');
    }
}
vm.delRole = function () {
    if (vm.selectdRole() != '') {
        vm.selectdRole().entityAspect.setDeleted();
        saveSingleEntity(vm.selectdRole(), null);
        var match = ko.utils.arrayFirst(vm.Roles(), function (Role) {
            if (Role.UniqueId() === vm.selectdRole().UniqueId())
                return Role;
        });
        vm.Roles.remove(match);
    }
}
vm.getMenu = function (data) {
    setActive('_rolelist', data.Name());
    vm.selectdRole(data);
}

//***************************************
//* The code below is used for Account Management *
//***************************************

vm.AccList = ko.observableArray();
vm.AccFilter = ko.observableArray();
vm.selectAccount = ko.observable('');

var qrAcc = new breeze.EntityQuery().from("Accounts");
manager.executeQuery(qrAcc).then(function (data) {
    data.results.forEach(function (item) {
        vm.AccList.push(item);
        vm.AccFilter.push(item);
    });
}).fail(function (e) {
    alert(e);
});

vm.filter = function () {
    vm.AccFilter([]);
    if ($('#_status').val() != 'all') {
        ko.utils.arrayFirst(vm.AccList(), function (item) {
            if (item.Email().toLowerCase().indexOf($('#_mailname').val().toLowerCase()) !== -1 && item.Status() == $('#_status').val()) {
                vm.AccFilter.push(item);
            }
        });
    } else {
        ko.utils.arrayFirst(vm.AccList(), function (item) {
            if (item.Email().toLowerCase().indexOf($('#_mailname').val().toLowerCase()) !== -1) {
                vm.AccFilter.push(item);
            }
        });
    }
}


vm.getInf = function (data) {
    setActive('_acclist', data.Email());
    vm.selectAccount(data);
}
vm.enable = function () {
    $('#_load').show();
    vm.selectAccount().Status(1);
    manager.saveChanges([vm.selectAccount()]).fail(saveFailed);
    $('#_load').hide();
}
vm.disable = function () {
    $('#_load').show();
    vm.selectAccount().Status(2);
    manager.saveChanges([vm.selectAccount()]).fail(saveFailed);
    $('#_load').hide();
}